package gogogo.liwushuo.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import gogogo.liwushuo.R;
import gogogo.liwushuo.fragment.CategoryFragment;
import gogogo.liwushuo.fragment.CgLeftFragment;
import gogogo.liwushuo.fragment.HomeFragment;
import gogogo.liwushuo.fragment.ProfileFragment;
import gogogo.liwushuo.fragment.SelectorFragment;

/**
 *
 */
public class MainActivity extends AppCompatActivity {

    @InjectView(R.id.fragmentContainer)
    FrameLayout fragmentContainer;
    @InjectView(R.id.rg_home)
    RadioGroup rgHome;
    private RadioButton rbChecked;
    private FragmentManager fm;
    private List<Fragment> mList;
    //记录需要隐藏的fragment下标
    private int previousindex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        //初始化所有碎片
        initFragment();

        //初始化进入时候的显示界面
        initDatas();

        //设置监听
        setListener();
    }

    private void initFragment() {
        mList = new ArrayList<>();
        mList.add(HomeFragment.newInstance());
        mList.add(new SelectorFragment());
        mList.add(new CategoryFragment());
        mList.add(new ProfileFragment());

    }

    private void initDatas() {
        fm = getSupportFragmentManager();
        rbChecked = (RadioButton) rgHome.getChildAt(0);
        rbChecked.setChecked(true);
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.fragmentContainer,mList.get(0)).commit();

    }

    private void setListener() {
        rgHome.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                rbChecked = (RadioButton) group.findViewById(checkedId);
                FragmentTransaction ft = fm.beginTransaction();
                int index = rgHome.indexOfChild(rbChecked);
                if (!mList.get(index).isAdded()){
                    ft.add(R.id.fragmentContainer,mList.get(index));
                }
                if (index != previousindex){
                    ft.hide(mList.get(previousindex));
                }
                previousindex = index;
                ft.show(mList.get(index)).commit();
            }
        });
    }


}
